package common.project.epic.ui;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import common.project.epic.db.*;

public class EpicSettings extends TabActivity implements OnClickListener, OnItemSelectedListener, OnTabChangeListener {
	public static final String TAG = "Epic: EpicSettings Activity";
    public static final boolean DEBUG = EpicDebugUI.DEBUG;
    
    private static final int NUMBER_OF_CATEGORIES = 16;
    private static final int NUMBER_OF_NOTIFICATION_TYPE = 3;
    private static final int NUMBER_OF_NOTIFICATION_BEHAVIOR = 5;
    private static final int INTEREST_AREA_IND_BUILDING = 0;
	private static final int INTEREST_AREA_VAL_BUILDING = 10; // [tens of meters]
	private static final int INTEREST_AREA_IND_QUARTER = 1;
	private static final int INTEREST_AREA_VAL_QUARTER = 100; // [tens of meters]
	private static final int INTEREST_AREA_IND_CITY = 2;
	private static final int INTEREST_AREA_VAL_CITY = 1000; // [tens of meters]
	private static final int INTEREST_AREA_IND_WORLD = 3;
	private static final int INTEREST_AREA_VAL_WORLD = 65000; // [tens of meters]
	private static final int INTEREST_PERIOD_IND_WEEK = 0;
	private static final int INTEREST_PERIOD_VAL_WEEK = 60*60*24*7; // [seconds]
	private static final int INTEREST_PERIOD_IND_MONTH = 1;
	private static final int INTEREST_PERIOD_VAL_MONTH = 60*60*24*30; // [seconds]
	private static final int INTEREST_PERIOD_IND_YEAR = 2;
	private static final int INTEREST_PERIOD_VAL_YEAR = 60*60*24*365; // [seconds]
	private static final int INTEREST_PERIOD_IND_INFINITY = 3;
	private static final int INTEREST_PERIOD_VAL_INFINITY = 60*60*24*365*10; // [seconds]
	private static final long MIN_QUARANTINE = 20000000;
	private static final long MAX_QUARANTINE = 100000000;
        
//    private CheckBox category_general_CB;
//	private CheckBox category_games_CB;
//	private CheckBox category_advertisements_CB;
//	private CheckBox category_suggestions_CB;
//	private CheckBox category_events_CB;
    private CheckBox categoryGeneralLiked;
	private CheckBox categoryGamesLiked;
	private CheckBox categoryAdvertisementsLiked;
	private CheckBox categorySuggestionsLiked;
	private CheckBox categoryEventsLiked;
	private CheckBox categoryGeneralBanned;
	private CheckBox categoryGamesBanned;
	private CheckBox categoryAdvertisementsBanned;
	private CheckBox categorySuggestionsBanned;
	private CheckBox categoryEventsBanned;
//	private boolean[] pref_categories = new boolean[NUMBER_OF_CATEGORIES];
	private int[] pref_categories = new int[NUMBER_OF_CATEGORIES]; // 0 = not checked, 1 = liked, 2 = banned
	
	private SeekBar quarantineSlider;
	private long quarantineValue;
	
	private CheckBox notification_sound_CB;
	private CheckBox notification_vibration_CB;
	private CheckBox notification_light_CB;
	private boolean[] notification_type = new boolean[NUMBER_OF_NOTIFICATION_TYPE];
	
	private CheckBox notification_always_CB;
	private CheckBox notification_never_CB;
	private CheckBox notification_matching_categories_CB; // liked categories
	private CheckBox notification_geo_span_CB;
	private CheckBox notification_time_span_CB;	
	private boolean[] notification_behavior = new boolean[NUMBER_OF_NOTIFICATION_BEHAVIOR];
	
	private Spinner select_interest_area_spinner;
	private int interest_area_ind;
	private int interest_area_val;

	private Spinner select_interest_period_spinner;
	private int interest_period_ind;
	private int interest_period_val;
	
	ImageButton select_default_msg_location_IB;
	private double default_altitude;
	private double default_latitude;
	private double default_longitude;
	private String default_place;
	
	private CheckBox categoryGeneralTypical;
	private CheckBox categoryGamesTypical;
	private CheckBox categoryAdvertisementsTypical;
	private CheckBox categorySuggestionsTypical;
	private CheckBox categoryEventsTypical;
	private boolean[] typ_categories = new boolean[NUMBER_OF_CATEGORIES];
	
	private Spinner select_default_msg_area_spinner;
	private int default_msg_area_ind;
	private int default_msg_area_val;
	private Spinner select_default_msg_period_spinner;
	private int default_msg_period_ind;
	private int default_msg_period_val;
	
	private CheckBox blowOnMicCB; 
	private boolean blowOnMic;
	private static TabHost tabHost;
	Resources res;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.epicsettings);
        if(DEBUG) {
    		Log.d(TAG, "onCreate()");
    	}
        
        res = getResources();
        
        tabHost = getTabHost();  
        
		TabHost.TabSpec spec;  
		spec = tabHost.newTabSpec("preferences")
				.setIndicator("Preferences",res.getDrawable(R.drawable.ic_tab1_settings))
				.setContent(R.id.epicsettingsTab1);  
		tabHost.addTab(spec);  
		spec = tabHost.newTabSpec("notifications")
				.setIndicator("Set Notification type and behavior",res.getDrawable(R.drawable.ic_tab2_settings))
				.setContent(R.id.epicsettingsTab2);
		tabHost.addTab(spec);  
		spec = tabHost.newTabSpec("typicalValues")
				.setIndicator("Set typical message properties",res.getDrawable(R.drawable.ic_tab3_settings))
				.setContent(R.id.epicsettingsTab3);
		tabHost.addTab(spec);  
		spec = tabHost.newTabSpec("webAndSynch")
				.setIndicator("Web and Synchronization",res.getDrawable(R.drawable.ic_tab4_settings))
				.setContent(R.id.epicsettingsTab4);
		tabHost.addTab(spec);  
		tabHost.setCurrentTab(0);
        
        categoryGeneralLiked = (CheckBox) findViewById(R.id.epicsettingsGeneralLiked);
        categoryGamesLiked = (CheckBox) findViewById(R.id.epicsettingsGamesLiked);
        categoryAdvertisementsLiked = (CheckBox) findViewById(R.id.epicsettingsAdvertisementsLiked);
        categorySuggestionsLiked = (CheckBox) findViewById(R.id.epicsettingsSuggestionsLiked);
        categoryEventsLiked = (CheckBox) findViewById(R.id.epicsettingsEventsLiked);
        categoryGeneralBanned = (CheckBox) findViewById(R.id.epicsettingsGeneralBanned);
        categoryGamesBanned = (CheckBox) findViewById(R.id.epicsettingsGamesBanned);
        categoryAdvertisementsBanned = (CheckBox) findViewById(R.id.epicsettingsAdvertisementsBanned);
        categorySuggestionsBanned = (CheckBox) findViewById(R.id.epicsettingsSuggestionsBanned);
        categoryEventsBanned = (CheckBox) findViewById(R.id.epicsettingsEventsBanned);
        
        quarantineSlider = (SeekBar) findViewById(R.id.epicsettingsQuarantineSB);
        
        blowOnMicCB = (CheckBox) findViewById(R.id.epicsettingsBlowOnMic);
        
        notification_sound_CB = (CheckBox) findViewById(R.id.notification_sound_CB);
        notification_vibration_CB = (CheckBox) findViewById(R.id.notification_vibration_CB);
        notification_light_CB = (CheckBox) findViewById(R.id.notification_light_CB);
        
        notification_always_CB = (CheckBox) findViewById(R.id.notification_always_CB);
        notification_never_CB = (CheckBox) findViewById(R.id.notification_never_CB);
        notification_matching_categories_CB = (CheckBox) findViewById(R.id.notification_matching_categories_CB);
        notification_geo_span_CB = (CheckBox) findViewById(R.id.notification_geo_span_CB);
        select_interest_area_spinner = (Spinner) findViewById(R.id.select_interest_area_spinner);
        notification_time_span_CB = (CheckBox) findViewById(R.id.notification_time_span_CB);
        select_interest_period_spinner = (Spinner) findViewById(R.id.select_interest_period_spinner);
        
        categoryGeneralTypical = (CheckBox) findViewById(R.id.epicsettingsGeneralTypical);
        categoryGamesTypical = (CheckBox) findViewById(R.id.epicsettingsGamesTypical);
        categoryAdvertisementsTypical = (CheckBox) findViewById(R.id.epicsettingsAdvertisementsTypical);
        categorySuggestionsTypical = (CheckBox) findViewById(R.id.epicsettingsSuggestionsTypical);
        categoryEventsTypical = (CheckBox) findViewById(R.id.epicsettingsEventsTypical);
        
        select_default_msg_location_IB = (ImageButton) findViewById(R.id.default_location_IB);
        
        select_default_msg_area_spinner = (Spinner) findViewById(R.id.select_default_msg_area_spinner);
        select_default_msg_period_spinner = (Spinner) findViewById(R.id.select_default_msg_period_spinner);
        
        
        categoryGeneralLiked.setOnClickListener(this);
        categoryGamesLiked.setOnClickListener(this);
        categoryAdvertisementsLiked.setOnClickListener(this);
        categorySuggestionsLiked.setOnClickListener(this);
        categoryEventsLiked.setOnClickListener(this);
        categoryGeneralBanned.setOnClickListener(this);
        categoryGamesBanned.setOnClickListener(this);
        categoryAdvertisementsBanned.setOnClickListener(this);
        categorySuggestionsBanned.setOnClickListener(this);
        categoryEventsBanned.setOnClickListener(this);
        
        quarantineSlider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				quarantineValue = (long)((((double)progress/(double)quarantineSlider.getMax()))*(double)(MAX_QUARANTINE-MIN_QUARANTINE)) + MIN_QUARANTINE;
				Log.d("EpicSettings", "quarantineValue = " + quarantineValue);
			}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {}
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        
        blowOnMicCB.setOnClickListener(this);
        
        notification_sound_CB.setOnClickListener(this);
        notification_vibration_CB.setOnClickListener(this);
        notification_light_CB.setOnClickListener(this);
        
        notification_always_CB.setOnClickListener(this);
        notification_never_CB.setOnClickListener(this);
        notification_matching_categories_CB.setOnClickListener(this);
        notification_geo_span_CB.setOnClickListener(this);
        notification_time_span_CB.setOnClickListener(this);
        
        categoryGeneralTypical.setOnClickListener(this);
        categoryGamesTypical.setOnClickListener(this);
        categoryAdvertisementsTypical.setOnClickListener(this);
        categorySuggestionsTypical.setOnClickListener(this);
        categoryEventsTypical.setOnClickListener(this);
        
        select_default_msg_location_IB.setOnClickListener(this);
        
        setTabColor(tabHost);
        
        tabHost.setOnTabChangedListener(this);
    }
    
    @Override
    protected void onPause() {
    	saveSettings();
    	super.onPause();
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	// retrieve the specific (logged in) user preference file
        CurrentUser.readCurrentUserSettings(getApplicationContext());
        
        String categoriesString = CurrentUser.getPrefCategories();
        for(int i=0; i<NUMBER_OF_CATEGORIES; i++) {
        	if(categoriesString.charAt(i)=='0') {
        		// no pref
        		pref_categories[i] = 0;
        		switch(i) {
					case(0): {categoryGeneralLiked.setChecked(false); categoryGeneralBanned.setChecked(false); break;}
					case(1): {categoryGamesLiked.setChecked(false); categoryGamesBanned.setChecked(false); break;}
					case(2): {categoryAdvertisementsLiked.setChecked(false); categoryAdvertisementsBanned.setChecked(false); break;}
					case(3): {categorySuggestionsLiked.setChecked(false); categorySuggestionsBanned.setChecked(false); break;}
					case(4): {categoryEventsLiked.setChecked(false); categoryEventsBanned.setChecked(false); break;}
        		}
        	}
        	if(categoriesString.charAt(i)=='1') {
        		// liked
        		pref_categories[i] = 1;
        		switch(i) {
					case(0): {categoryGeneralLiked.setChecked(true); categoryGeneralBanned.setChecked(false); break;}
					case(1): {categoryGamesLiked.setChecked(true); categoryGamesBanned.setChecked(false); break;}
					case(2): {categoryAdvertisementsLiked.setChecked(true); categoryAdvertisementsBanned.setChecked(false); break;}
					case(3): {categorySuggestionsLiked.setChecked(true); categorySuggestionsBanned.setChecked(false); break;}
					case(4): {categoryEventsLiked.setChecked(true); categoryEventsBanned.setChecked(false); break;}
	    		}
        	}
			if(categoriesString.charAt(i)=='2') {
				// banned
				pref_categories[i] = 2;
				switch(i) {
					case(0): {categoryGeneralLiked.setChecked(false); categoryGeneralBanned.setChecked(true); break;}
					case(1): {categoryGamesLiked.setChecked(false); categoryGamesBanned.setChecked(true); break;}
					case(2): {categoryAdvertisementsLiked.setChecked(false); categoryAdvertisementsBanned.setChecked(true); break;}
					case(3): {categorySuggestionsLiked.setChecked(false); categorySuggestionsBanned.setChecked(true); break;}
					case(4): {categoryEventsLiked.setChecked(false); categoryEventsBanned.setChecked(true); break;}
	    		}
			}
        }
        
        quarantineValue = CurrentUser.getQuarantineValue();
        // set the value of 
        quarantineSlider.setProgress((int)((double)(quarantineValue - MIN_QUARANTINE)*((double)quarantineSlider.getMax()/(double)(MAX_QUARANTINE - MIN_QUARANTINE))));
        
        blowOnMic = CurrentUser.getBlowOnMic();
        blowOnMicCB.setChecked(blowOnMic);
        
        String notification_type_str = CurrentUser.getNotificationType();
        notification_type[0] = notification_type_str.substring(0,1).equals("1") ? true : false;
        notification_sound_CB.setChecked(notification_type[0]);
        notification_type[1] = notification_type_str.substring(1,2).equals("1") ? true : false; 
        notification_vibration_CB.setChecked(notification_type[1]);
        notification_type[2] = notification_type_str.substring(2,3).equals("1") ? true : false;
        notification_light_CB.setChecked(notification_type[2]);
        
        String notification_behavior_str = CurrentUser.getNotificationBehavior();
        notification_behavior[0] = notification_behavior_str.substring(0,1).equals("1") ? true : false;
        notification_always_CB.setChecked(notification_behavior[0]);
        notification_behavior[1] = notification_behavior_str.substring(1,2).equals("1") ? true : false;
        notification_never_CB.setChecked(notification_behavior[1]);
        notification_behavior[2] = notification_behavior_str.substring(2,3).equals("1") ? true : false;
        notification_matching_categories_CB.setChecked(notification_behavior[2]);
        notification_behavior[3] = notification_behavior_str.substring(3,4).equals("1") ? true : false;
        notification_geo_span_CB.setChecked(notification_behavior[3]);
        notification_behavior[4] = notification_behavior_str.substring(4,5).equals("1") ? true : false;
        notification_time_span_CB.setChecked(notification_behavior[4]);
        
        String typCategoriesString = CurrentUser.getTypicalCategories();
        typ_categories[0] = typCategoriesString.substring(0,1).equals("1") ? true : false;
        categoryGeneralTypical.setChecked(typ_categories[0]);
        typ_categories[1] = typCategoriesString.substring(1,2).equals("1") ? true : false;
        categoryGamesTypical.setChecked(typ_categories[1]);
        typ_categories[2] = typCategoriesString.substring(2,3).equals("1") ? true : false;
        categoryAdvertisementsTypical.setChecked(typ_categories[2]);
        typ_categories[3] = typCategoriesString.substring(3,4).equals("1") ? true : false;
        categorySuggestionsTypical.setChecked(typ_categories[3]);
        typ_categories[4] = typCategoriesString.substring(4,5).equals("1") ? true : false;
        categoryEventsTypical.setChecked(typ_categories[4]);
        
        default_altitude = CurrentUser.getDefaultMsgAltitude();
        default_latitude = CurrentUser.getDefaultMsgLatitude();
        default_longitude = CurrentUser.getDefaultMsgLongitude();
        default_place = CurrentUser.getDefaultMsgPlace();
        
        ArrayAdapter<CharSequence> select_interest_area_adapter = 
        	ArrayAdapter.createFromResource(this, R.array.select_interest_area_array, android.R.layout.simple_spinner_item);
        select_interest_area_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        select_interest_area_spinner.setAdapter(select_interest_area_adapter);
        select_interest_area_spinner.setOnItemSelectedListener(this);
        // retrieve the preferences values or set the default value
        interest_area_val = CurrentUser.getGeoSpan();
        switch(interest_area_val) {
			case(INTEREST_AREA_VAL_BUILDING): {interest_area_ind = INTEREST_AREA_IND_BUILDING; break;}
			case(INTEREST_AREA_VAL_QUARTER): {interest_area_ind = INTEREST_AREA_IND_QUARTER; break;}
			case(INTEREST_AREA_VAL_CITY): {interest_area_ind = INTEREST_AREA_IND_CITY; break;}
			case(INTEREST_AREA_VAL_WORLD): {interest_area_ind = INTEREST_AREA_IND_WORLD; break;}
        }
        select_interest_area_spinner.setSelection(interest_area_ind);
        
        ArrayAdapter<CharSequence> select_interest_period_adapter = 
        	ArrayAdapter.createFromResource(this, R.array.select_interest_period_array, android.R.layout.simple_spinner_item);
        select_interest_period_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        select_interest_period_spinner.setAdapter(select_interest_period_adapter);
        select_interest_period_spinner.setOnItemSelectedListener(this);
        // retrieve the preferences values or set the default value
        interest_period_val = CurrentUser.getTimeSpan();
        switch(interest_period_val) {
			case(INTEREST_PERIOD_VAL_WEEK): {interest_period_ind = INTEREST_PERIOD_IND_WEEK; break;}
			case(INTEREST_PERIOD_VAL_MONTH): {interest_period_ind = INTEREST_PERIOD_IND_MONTH; break;}
			case(INTEREST_PERIOD_VAL_YEAR): {interest_period_ind = INTEREST_PERIOD_IND_YEAR; break;}
			case(INTEREST_PERIOD_VAL_INFINITY): {interest_period_ind = INTEREST_PERIOD_IND_INFINITY; break;}
        }
        select_interest_period_spinner.setSelection(interest_period_ind);
        
        ArrayAdapter<CharSequence> select_default_msg_area_adapter = 
            	ArrayAdapter.createFromResource(this, R.array.select_interest_area_array, android.R.layout.simple_spinner_item);
        select_default_msg_area_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        select_default_msg_area_spinner.setAdapter(select_default_msg_area_adapter);
        select_default_msg_area_spinner.setOnItemSelectedListener(this);
        // retrieve the preferences values or set the default value
        default_msg_area_val = CurrentUser.getDefaultMsgGeoSpan();
        switch(default_msg_area_val) {
			case(INTEREST_AREA_VAL_BUILDING): {default_msg_area_ind = INTEREST_AREA_IND_BUILDING; break;}
			case(INTEREST_AREA_VAL_QUARTER): {default_msg_area_ind = INTEREST_AREA_IND_QUARTER; break;}
			case(INTEREST_AREA_VAL_CITY): {default_msg_area_ind = INTEREST_AREA_IND_CITY; break;}
			case(INTEREST_AREA_VAL_WORLD): {default_msg_area_ind = INTEREST_AREA_IND_WORLD; break;}
        }
        select_default_msg_area_spinner.setSelection(default_msg_area_ind);
            
		ArrayAdapter<CharSequence> select_default_msg_period_adapter = 
				ArrayAdapter.createFromResource(this, R.array.select_default_period_array, android.R.layout.simple_spinner_item);
		select_default_msg_period_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		select_default_msg_period_spinner.setAdapter(select_default_msg_period_adapter);
		select_default_msg_period_spinner.setOnItemSelectedListener(this);
		// retrieve the preferences values or set the default value
		default_msg_period_val = CurrentUser.getDefaultMsgTimeSpan();
		switch(default_msg_period_val) {
			case(INTEREST_PERIOD_VAL_WEEK): {default_msg_period_ind = INTEREST_PERIOD_IND_WEEK; break;}
			case(INTEREST_PERIOD_VAL_MONTH): {default_msg_period_ind = INTEREST_PERIOD_IND_MONTH; break;}
			case(INTEREST_PERIOD_VAL_YEAR): {default_msg_period_ind = INTEREST_PERIOD_IND_YEAR; break;}
//			case(INTEREST_PERIOD_VAL_INFINITY): {default_msg_period_ind = INTEREST_PERIOD_IND_INFINITY; break;}
		}
		select_default_msg_period_spinner.setSelection(default_msg_period_ind);
		
		checkIfNotificationAlwaysIsChecked();
    }
    
  //###############################################################
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
//    	savedInstanceState.putIntArray("pref_categories", pref_categories);
//    	savedInstanceState.putBooleanArray("notification_type", notification_type);
//    	savedInstanceState.putBooleanArray("notification_behavior", notification_behavior);
//    	savedInstanceState.putInt("interest_area_ind", interest_area_ind);
//    	savedInstanceState.putInt("interest_area_val", interest_area_val);
//    	savedInstanceState.putInt("interest_period_ind", interest_period_ind);
//    	savedInstanceState.putInt("interest_period_val", interest_period_val);
//    	savedInstanceState.putInt("default_msg_area_ind", default_msg_area_ind);
//    	savedInstanceState.putInt("default_msg_area_val", default_msg_area_val);
//    	savedInstanceState.putInt("default_msg_period_ind", default_msg_period_ind);
//    	savedInstanceState.putInt("default_msg_period_val", default_msg_period_val);
//    	
//    	savedInstanceState.putDouble("default_altitude", default_altitude);
//    	savedInstanceState.putDouble("default_latitude", default_latitude);
//    	savedInstanceState.putDouble("default_longitude", default_longitude);
    	super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
//    	pref_categories = savedInstanceState.getIntArray("pref_categories");
//    	notification_type = savedInstanceState.getBooleanArray("notification_type");
//    	notification_behavior = savedInstanceState.getBooleanArray("notification_behavior");
//    	interest_area_ind = savedInstanceState.getInt("interest_area_ind");
//    	interest_area_val = savedInstanceState.getInt("interest_area_val");
//    	interest_period_ind = savedInstanceState.getInt("interest_period_ind");
//    	interest_period_val = savedInstanceState.getInt("interest_period_val");
//    	default_msg_area_ind = savedInstanceState.getInt("default_msg_area_ind");
//    	default_msg_area_val = savedInstanceState.getInt("default_msg_area_val");
//    	default_msg_period_ind = savedInstanceState.getInt("default_msg_period_ind");
//    	default_msg_period_val = savedInstanceState.getInt("default_msg_period_val");
//    	
//    	default_altitude = savedInstanceState.getDouble("default_altitude");
//    	default_latitude = savedInstanceState.getDouble("default_latitude");
//    	default_longitude = savedInstanceState.getDouble("default_longitude");
    }
    //###############################################################
    
    private void checkIfNotificationAlwaysIsChecked() {
    	if(notification_always_CB.isChecked()) {
    		// the other fields in Notification behavior lose focus
    		notification_never_CB.setChecked(false);
    		notification_behavior[1] = false;
    		notification_matching_categories_CB.setChecked(false);
    		notification_behavior[2] = false;
    		notification_geo_span_CB.setChecked(false);
    		notification_behavior[3] = false;
    		notification_time_span_CB.setChecked(false);
    		notification_behavior[4] = false;
    		
    		notification_never_CB.setEnabled(false);
    		notification_matching_categories_CB.setEnabled(false);
    		notification_geo_span_CB.setEnabled(false);
    		select_interest_area_spinner.setEnabled(false);
    		notification_time_span_CB.setEnabled(false);
    		select_interest_period_spinner.setEnabled(false);
    	}
    	else if(notification_never_CB.isChecked()) {
    		// the other fields in Notification behavior lose focus
    		notification_always_CB.setChecked(false);
    		notification_behavior[0] = false;
    		notification_matching_categories_CB.setChecked(false);
    		notification_behavior[2] = false;
    		notification_geo_span_CB.setChecked(false);
    		notification_behavior[3] = false;
    		notification_time_span_CB.setChecked(false);
    		notification_behavior[4] = false;
    		
    		notification_always_CB.setEnabled(false);
    		notification_matching_categories_CB.setEnabled(false);
    		notification_geo_span_CB.setEnabled(false);
    		select_interest_area_spinner.setEnabled(false);
    		notification_time_span_CB.setEnabled(false);
    		select_interest_period_spinner.setEnabled(false);
    	}
    	else {
    		// all the fields in Notification behavior get focus
    		notification_always_CB.setEnabled(true);
    		notification_never_CB.setEnabled(true);
    		notification_matching_categories_CB.setEnabled(true);
    		notification_geo_span_CB.setEnabled(true);
    		select_interest_area_spinner.setEnabled(true);
    		notification_time_span_CB.setEnabled(true);
    		select_interest_period_spinner.setEnabled(true);
    	}
    }

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.epicsettingsGeneralLiked) {
			if(categoryGeneralLiked.isChecked()) {categoryGeneralBanned.setChecked(false); pref_categories[0] = 1;}
			else {pref_categories[0] = 0;}
		}
		if(v.getId() == R.id.epicsettingsGeneralBanned) {
			if(categoryGeneralBanned.isChecked()) {categoryGeneralLiked.setChecked(false); pref_categories[0] = 2;}
			else {pref_categories[0] = 0;}
		}
		
		if(v.getId() == R.id.epicsettingsGamesLiked) {
			if(categoryGamesLiked.isChecked()) {categoryGamesBanned.setChecked(false); pref_categories[1] = 1;}
			else {pref_categories[1] = 0;}
		}
		if(v.getId() == R.id.epicsettingsGamesBanned) {
			if(categoryGamesBanned.isChecked()) {categoryGamesLiked.setChecked(false); pref_categories[1] = 2;}
			else {pref_categories[1] = 0;}
		}
		
		if(v.getId() == R.id.epicsettingsAdvertisementsLiked) {
			if(categoryAdvertisementsLiked.isChecked()) {categoryAdvertisementsBanned.setChecked(false); pref_categories[2] = 1;}
			else {pref_categories[2] = 0;}
		}
		if(v.getId() == R.id.epicsettingsAdvertisementsBanned) {
			if(categoryAdvertisementsBanned.isChecked()) {categoryAdvertisementsLiked.setChecked(false); pref_categories[2] = 2;}
			else {pref_categories[2] = 0;}
		}
		
		if(v.getId() == R.id.epicsettingsSuggestionsLiked) {
			if(categorySuggestionsLiked.isChecked()) {categorySuggestionsBanned.setChecked(false); pref_categories[3] = 1;}
			else {pref_categories[3] = 0;}
		}
		if(v.getId() == R.id.epicsettingsSuggestionsBanned) {
			if(categorySuggestionsBanned.isChecked()) {categorySuggestionsLiked.setChecked(false); pref_categories[3] = 2;}
			else {pref_categories[3] = 0;}
		}
		
		if(v.getId() == R.id.epicsettingsEventsLiked) {
			if(categoryEventsLiked.isChecked()) {categoryEventsBanned.setChecked(false); pref_categories[4] = 1;}
			else {pref_categories[4] = 0;}
		}
		if(v.getId() == R.id.epicsettingsEventsBanned) {
			if(categoryEventsBanned.isChecked()) {categoryEventsLiked.setChecked(false); pref_categories[4] = 2;}
			else {pref_categories[4] = 0;}
		}
		
		if(v.getId() == R.id.epicsettingsBlowOnMic) {
			if(blowOnMicCB.isChecked()) {blowOnMic = true;} else {blowOnMic = false;}
		}
		
		if(v.getId() == R.id.notification_sound_CB) {
			if(notification_sound_CB.isChecked()) {notification_type[0] = true;} else {notification_type[0] = false;}
		}
		if(v.getId() == R.id.notification_vibration_CB) {
			if(notification_vibration_CB.isChecked()) {notification_type[1] = true;} else {notification_type[1] = false;}
		}
		if(v.getId() == R.id.notification_light_CB) {
			if(notification_light_CB.isChecked()) {notification_type[2] = true;} else {notification_type[2] = false;}
		}
		
		if(v.getId() == R.id.notification_always_CB) {
			if(notification_always_CB.isChecked()) {notification_behavior[0] = true;} else {notification_behavior[0] = false;}
			checkIfNotificationAlwaysIsChecked();
		}
		if(v.getId() == R.id.notification_never_CB) {
			if(notification_never_CB.isChecked()) {notification_behavior[1] = true;} else {notification_behavior[1] = false;}
			checkIfNotificationAlwaysIsChecked();
		}
		if(v.getId() == R.id.notification_matching_categories_CB) {
			if(notification_matching_categories_CB.isChecked()) {notification_behavior[2] = true;} else {notification_behavior[2] = false;}
		}
		if(v.getId() == R.id.notification_geo_span_CB) {
			if(notification_geo_span_CB.isChecked()) {notification_behavior[3] = true;} else {notification_behavior[3] = false;}
		}
		if(v.getId() == R.id.notification_time_span_CB) {
			if(notification_time_span_CB.isChecked()) {notification_behavior[4] = true;} else {notification_behavior[4] = false;}
		}
		
		//####
		if(v.getId() == R.id.default_location_IB) {
			if(isOnline()) {
				CurrentUser.readCurrentUserSettings(getApplicationContext());
				Intent mapIntent = new Intent(this, EpicMapActivity.class);
				mapIntent.putExtra("inLat", CurrentUser.getDefaultMsgLatitude());
				mapIntent.putExtra("inLon", CurrentUser.getDefaultMsgLongitude());
				mapIntent.putExtra("settableMsgPosition", true);
				startActivityForResult(mapIntent, MAP_SUBACTIVITY);
			}
			else {
				Toast.makeText(getApplicationContext(), "to set message home location \n" +
						"data connection is needed", Toast.LENGTH_LONG).show();
			}
		}
		
		if(v.getId() == R.id.epicsettingsGeneralTypical) {
			if(categoryGeneralTypical.isChecked()) {typ_categories[0] = true;} else {typ_categories[0] = false;} 
		}
		if(v.getId() == R.id.epicsettingsGamesTypical) {
			if(categoryGamesTypical.isChecked()) {typ_categories[1] = true;} else {typ_categories[1] = false;} 
		}
		if(v.getId() == R.id.epicsettingsAdvertisementsTypical) {
			if(categoryAdvertisementsTypical.isChecked()) {typ_categories[2] = true;} else {typ_categories[2] = false;} 
		}
		if(v.getId() == R.id.epicsettingsSuggestionsTypical) {
			if(categorySuggestionsTypical.isChecked()) {typ_categories[3] = true;} else {typ_categories[3] = false;} 
		}
		if(v.getId() == R.id.epicsettingsEventsTypical) {
			if(categoryEventsTypical.isChecked()) {typ_categories[4] = true;} else {typ_categories[4] = false;} 
		}
		
	}
	
	public void saveSettings() {
		String prefCategories = "";
		for (int item : pref_categories) {
			if(item==0) {prefCategories = prefCategories + "0";} 
			else if(item==1) {prefCategories = prefCategories + "1";}
			else if(item==2) {prefCategories = prefCategories + "2";}
		}			
		CurrentUser.setPrefCategories(prefCategories);
		
		CurrentUser.setQuarantineValue(quarantineValue);
		
		CurrentUser.setBlowOnMic(blowOnMic);
		
		String notificationType = "";
		for (boolean item : notification_type) {
			if(item) {notificationType = notificationType + "1";} else {notificationType = notificationType + "0";}
		}
		CurrentUser.setNotificationType(notificationType);
		
		String notificationBehavior = "";
		for (boolean item : notification_behavior) {
			if(item) {notificationBehavior = notificationBehavior + "1";} else {notificationBehavior = notificationBehavior + "0";}
		}
		CurrentUser.setNotificationBehavior(notificationBehavior);
		
		CurrentUser.setGeoSpan(interest_area_val);
		
		CurrentUser.setTimeSpan(interest_period_val);
		
		boolean noTypCatChecked = true;
		for (boolean item : typ_categories) {
			if(item) {noTypCatChecked = false; break;}
		}
		if(noTypCatChecked) {
			typ_categories[0] = true;
		}
		String typCategories = "";
		for (boolean item : typ_categories) {
			if(item) {typCategories = typCategories + "1";} else {typCategories = typCategories + "0";}
		}
		
		CurrentUser.setTypicalCategories(typCategories);
		
		CurrentUser.setDefaultMsgAltitude(default_altitude);
		CurrentUser.setDefaultMsgLatitude(default_latitude);
		CurrentUser.setDefaultMsgLongitude(default_longitude);
		CurrentUser.setDefaultMsgPlace(default_place);
		
		CurrentUser.setDefaultMsgGeoSpan(default_msg_area_val);
		
		CurrentUser.setDefaultMsgTimeSpan(default_msg_period_val);
		
		CurrentUser.writeCurrentUserSettings(getApplicationContext());
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		if(parent.getId() == R.id.select_interest_area_spinner) {
			switch(pos) {
				case(INTEREST_AREA_IND_BUILDING): {interest_area_val = INTEREST_AREA_VAL_BUILDING; break;}
				case(INTEREST_AREA_IND_QUARTER): {interest_area_val = INTEREST_AREA_VAL_QUARTER; break;}
				case(INTEREST_AREA_IND_CITY): {interest_area_val = INTEREST_AREA_VAL_CITY; break;}
				case(INTEREST_AREA_IND_WORLD): {interest_area_val = INTEREST_AREA_VAL_WORLD; break;}
			}
		}
		
		if(parent.getId() == R.id.select_interest_period_spinner) {
			switch(pos) {
				case(INTEREST_PERIOD_IND_WEEK): {interest_period_val = INTEREST_PERIOD_VAL_WEEK; break;}
				case(INTEREST_PERIOD_IND_MONTH): {interest_period_val = INTEREST_PERIOD_VAL_MONTH; break;}
				case(INTEREST_PERIOD_IND_YEAR): {interest_period_val = INTEREST_PERIOD_VAL_YEAR; break;}
				case(INTEREST_PERIOD_IND_INFINITY): {interest_period_val = INTEREST_PERIOD_VAL_INFINITY; break;}
			}
		}
		
		if(parent.getId() == R.id.select_default_msg_area_spinner) {
			switch(pos) {
				case(INTEREST_AREA_IND_BUILDING): {default_msg_area_val = INTEREST_AREA_VAL_BUILDING; break;}
				case(INTEREST_AREA_IND_QUARTER): {default_msg_area_val = INTEREST_AREA_VAL_QUARTER; break;}
				case(INTEREST_AREA_IND_CITY): {default_msg_area_val = INTEREST_AREA_VAL_CITY; break;}
				case(INTEREST_AREA_IND_WORLD): {default_msg_area_val = INTEREST_AREA_VAL_WORLD; break;}
			}
		}
		
		if(parent.getId() == R.id.select_default_msg_period_spinner) {
			switch(pos) {
				case(INTEREST_PERIOD_IND_WEEK): {default_msg_period_val = INTEREST_PERIOD_VAL_WEEK; break;}
				case(INTEREST_PERIOD_IND_MONTH): {default_msg_period_val = INTEREST_PERIOD_VAL_MONTH; break;}
				case(INTEREST_PERIOD_IND_YEAR): {default_msg_period_val = INTEREST_PERIOD_VAL_YEAR; break;}
//				case(INTEREST_PERIOD_IND_INFINITY): {default_msg_period_val = INTEREST_PERIOD_VAL_INFINITY; break;}
			}
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
	}
	
	private static final int MAP_SUBACTIVITY = 1;
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) { 
        super.onActivityResult(requestCode, resultCode, returnedIntent);         
        switch(requestCode) { 
	        case MAP_SUBACTIVITY: {
	    		if(resultCode == RESULT_OK) {
	    			default_altitude = 0;
	    			default_latitude = returnedIntent.getDoubleExtra("outLat", 0);
	    			default_longitude = returnedIntent.getDoubleExtra("outLon", 0);
	    			
	    			Geocoder geocoder;
	    			List<Address> addresses = null;
	    			geocoder = new Geocoder(this, Locale.getDefault());
	    			String default_address = null;
	    			String default_city = null;
	    			String default_country = null;
	    			try {
						addresses = geocoder.getFromLocation(default_latitude, default_longitude, 1);
						default_address = addresses.get(0).getAddressLine(0);
		    			default_city = addresses.get(0).getAddressLine(1);
		    			default_country = addresses.get(0).getAddressLine(2);
					} catch (IOException e) {
						e.printStackTrace();
					}
	    			if(default_city!=null) {
	    				default_place = default_city;
	    			}
	    			
	    			CurrentUser.readCurrentUserSettings(getApplicationContext());
	    			CurrentUser.setDefaultMsgAltitude(default_altitude);
	    			CurrentUser.setDefaultMsgLatitude(default_latitude);
	    			CurrentUser.setDefaultMsgLongitude(default_longitude);
	    			CurrentUser.setDefaultMsgPlace(default_place);
	    			
	    			CurrentUser.writeCurrentUserSettings(getApplicationContext());
	    		}
	    		else {}
	    		break;
	    	}
        }
	}
	
	// check if there is data connection
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if(ni != null){
			return cm.getActiveNetworkInfo().isConnectedOrConnecting();
		}
		else {
			return false;
		}
	}
	
	
	
	public static void setTabColor(TabHost tabhost) {
	    for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
	    {
	    	
	        tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff")); //unselected
	    }
	    tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#37c0a2")); // selected
	}

	@Override
	public void onTabChanged(String tabId) {
		setTabColor(tabHost);
	}
	
}